package pers.cz.logtail;

import io.netty.channel.ChannelFuture;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import pers.cz.jefconfig.config.JefConfiguration;
import pers.cz.logtail.config.LogClientConfigItem;
import pers.cz.logtail.handler.LogListenner;
import pers.cz.netty.NettyClient;
import pers.cz.netty.config.NettyConfigItem;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @program: PostGirl-panent
 * @description: 客户端启动类
 * @author: Cheng Zhi
 * @create: 2022-10-05 12:16
 **/
public class ClientApplication {

    public static void main(String[] args) throws Exception {
        // 启动netty客户端
        String host = JefConfiguration.get(NettyConfigItem.NETTY_SERVER_IP);
        int prot = JefConfiguration.getInt(NettyConfigItem.NETTY_SERVER_PORT, 4567);

        NettyClient nettyClient =  new NettyClient(host, prot);
        ChannelFuture connect = nettyClient.connect();
        if (connect.sync().isSuccess()) {
            String listenPath = JefConfiguration.get(LogClientConfigItem.LOG_LISTEN_FILEPATH);
            String fileSuffix = JefConfiguration.get(LogClientConfigItem.LOG_LISTEN_SUFFIX);
            File directory = new File(listenPath);
            // 轮询间隔 5 秒
            long interval = TimeUnit.SECONDS.toMillis(JefConfiguration.getLong(LogClientConfigItem.LOG_LISTEN_INTERVALUE_TIME, 5));
            // 创建一个文件观察器用于处理文件的格式
            FileAlterationObserver observer = new FileAlterationObserver(directory, FileFilterUtils.and(
                    FileFilterUtils.fileFileFilter(),FileFilterUtils.suffixFileFilter(fileSuffix)));
            Map<String, Long> fileLineRember = new HashMap<>();
            //设置文件变化监听器
            observer.addListener(new LogListenner(fileLineRember, nettyClient));
            FileAlterationMonitor monitor = new FileAlterationMonitor(interval,observer);
            monitor.start();
        }
    }
}
